<template>
  <div>
    <el-dialog
      title="预定房间"
      class="gl_dialog_TitleLine"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :before-close="close"
      :show-close="false"
      width="592px"
    >
      <div v-if="isOrder || code === 'edit'" class="dialog_form">
        <el-form ref="form" class="gl_form_mini" :model="updateForm" :rules="form_rules" label-position="top">
          <el-form-item prop="checkInDate" label="预定时间">
            <el-input v-show="false" v-model.trim="updateForm.checkInDate" />
            <el-date-picker
              v-model="orderTime"
              type="daterange"
              size="mini"
              range-separator="至"
              start-placeholder="入住日期"
              end-placeholder="离店日期"
              style="width: 433px;"
              :picker-options="pickerOptions"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              @change="handleOrderTime"
            />
            <span v-if="updateForm.checkInDate" class="gl_pl_10">共{{ dayCount }}晚</span>
          </el-form-item>
          <el-form-item prop="reserveNumber" label="预定间数">
            <el-input-number v-model="updateForm.reserveNumber" :min="1" size="small" />
          </el-form-item>
          <el-form-item v-if="isShow" prop="hasExtraBed" label="是否加床">
            <el-radio-group v-model="updateForm.hasExtraBed">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="updateForm.hasExtraBed" prop="extraBedNumber" label="加床数量">
            <el-input v-model="updateForm.extraBedNumber" style="width: 134px" clearable placeholder="请输入" />
            <p class="gl_dis_ib gl_ml_10">
              <span class="popover">备注：每个房间只能添加一张床</span>
            </p>
          </el-form-item>
          <el-form-item prop="receptionName" label="预定人姓名">
            <el-input v-model="updateForm.receptionName" style="width: 307px" clearable placeholder="请输入预定人姓名" />
          </el-form-item>
          <el-form-item prop="receptionPhoneNumber" label="预定人电话号码">
            <el-input v-model="updateForm.receptionPhoneNumber" style="width: 307px" clearable placeholder="请输入预定人电话号码" />
          </el-form-item>
          <el-form-item prop="remark" label="备注">
            <el-input v-model="updateForm.remark" type="textarea" style="width: 503px" />
          </el-form-item>
        </el-form>
      </div>
      <div v-else style="line-height: 200px" class="gl_noData_mockTable">
        <p>对不起，此房型已经没有房间了，请选择其他房型！</p>
      </div>
      <el-row type="flex" justify="center">
        <el-col align="center">
          <el-button size="mini" style="border-radius: 8px;" @click="close()">{{ isOrder || code === 'edit' ? '取消' : '关闭' }}</el-button>
          <el-button v-if="isOrder || code === 'edit'" :loading="loading" type="primary" style="border-radius: 8px;" size="mini" @click="submit('form')">确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import validator from '@/lib/validate/index.js';
import {
  api_POST_EventsManagementHotelEntryHotelEntry, // 预定
  api_PUT_EventsManagementHotelEntryHotelEntryHotelEntryId // 修改
} from '@/extend/api/gameswaggerApi/app';
import {
  SiSTKWEventsManagementHotelEntryInput,
  SiSTKWEventsManagementUpdateHotelEntryInput
} from '@/lib/form/game/swaggerForm';
import { CopyData } from '@/lib';
export default {
  name: 'HotelOrder',
  data() {
    var validatePass2 = (rule, value, callback) => {
      // console.log(this.count, value)
      if (this.count < value && this.count !== null) {
        callback(new Error('房间库存不足，请重新选择'));
      } else {
        callback();
      }
    };
    return {
      dialogVisible: false,
      loading: false,
      lauchedRoomStocks: [],
      count: null,
      createForm: new SiSTKWEventsManagementHotelEntryInput(),
      updateForm: new SiSTKWEventsManagementUpdateHotelEntryInput(),
      room: {}, // 预订的房间数据
      code: '', // 预定 or 编辑
      entryId: '', // 预定时为后勤报名总表Id, 编辑为row.id
      isOrder: true, // 是否还有房间
      isShow: true, // 是否显示是否加床选项
      time: {}, // 后勤设置的酒店预定时间
      pickerOptions: { // 时间范围限制
        disabledDate: time => {
          var sDate = '';
          var nowDay = new Date();
          nowDay.setTime(nowDay.getTime() - 24 * 60 * 60 * 1000);
          var startDate = this.time.startDateTime.split('T')[0];
          var startDay = new Date(startDate);
          if (nowDay > startDay) {
            sDate = nowDay;
          } else {
            var staDate = startDate.split('-');
            sDate = new Date(staDate[0], staDate[1] - 1, staDate[2]);
          }
          var endDate = this.time.endDateTime.split('T')[0];
          var enDate = endDate.split('-');
          var eDate = new Date(enDate[0], enDate[1] - 1, enDate[2]);
          return time.getTime() < sDate || time.getTime() > eDate;
        }
      },
      orderTime: [],
      dayCount: 0, // 总天数
      form_rules: {
        checkInDate: [validator.required('预定时间不能为空')],
        reserveNumber: [
          validator.required('预定间数不能为空'),
          {
            validator: validatePass2, trigger: ['blur', 'change']
          }
        ],
        extraBedNumber: [
          validator.required('加床数量不能为空'),
          {
            validator(rule, value, callback) {
              callback(validator.checkPositiveNumber(value, '接车车辆数量只能是正整数'));
            },
            trigger: 'blur'
          }
        ],
        receptionName: [validator.required('预定人姓名不能为空')],
        receptionPhoneNumber: [
          validator.required('预定人电话号码不能为空'),
          {
            validator(rule, value, callback) {
              callback(validator.checkPhone(value, '电话号码格式错误'));
            },
            trigger: 'blur'
          }
        ]
      }
    };
  },
  methods: {
    open(room, code, id, time) {
      this.dialogVisible = true;
      this.room = room;
      this.code = code;
      this.isOrder = room.count > 0;
      this.time = time;
      if (code === 'order') {
        this.entryId = id;
        this.updateForm.reserveNumber = this.updateForm.reserveNumber || 1;
        this.updateForm.extraBedNumber = this.updateForm.extraBedNumber || null;
        this.isShow = this.room.hasExtraBed;
      }
      if (code === 'edit') {
        this.entryId = id;
        this.isShow = this.room.setHasExtraBed;
        this.orderTime = [room.checkInDate, room.checkOutDate];
        const day = new Date(room.checkOutDate).getTime() - new Date(room.checkInDate).getTime();
        this.dayCount = Math.floor(day / 86400000);
        CopyData(room, this.updateForm);
      }
    },
    // 处理预定时间
    handleOrderTime() {
      this.count = null;
      this.updateForm.checkInDate = this.orderTime && this.orderTime[0];
      this.updateForm.checkOutDate = this.orderTime && this.orderTime[1];
      const day = new Date(this.updateForm.checkOutDate).getTime() - new Date(this.updateForm.checkInDate).getTime();
      this.dayCount = Math.floor(day / 86400000);
      if (this.dayCount < 1) {
        this.orderTime = [];
        this.updateForm.checkInDate = '';
        this.updateForm.checkOutDate = '';
        this.$message({ type: 'error', message: '预定时间不可选择同一天，请重新选择！' });
      } else {
        var dates = [];
        const startDateTime = new Date(this.updateForm.checkInDate);
        const endDateTime = new Date(this.updateForm.checkOutDate);
        const daysBetween = Math.floor((endDateTime - startDateTime) / (1000 * 60 * 60 * 24));
        for (let i = 0; i < daysBetween; i++) {
          const date = new Date(startDateTime.getTime() + (i * 1000 * 60 * 60 * 24));
          dates.push({ dateTime: date.getFullYear() + '-' + ((date.getMonth() + 1) + '').padStart(2, '0') + '-' + (date.getDate() + '').padStart(2, '0'), quantity: null });
        }
        if (this.lauchedRoomStocks.length > 0) {
          for (let i = 0; i < this.lauchedRoomStocks.length; i++) {
            for (let j = 0; j < dates.length; j++) {
              if (this.lauchedRoomStocks[i].dateTime.split('T')[0] === dates[j].dateTime) {
                dates[j].quantity = this.lauchedRoomStocks[i].quantity;
              }
            }
          }
        }
        const minValue = dates.reduce((min, current) => {
          return current.quantity < min.quantity ? current : min;
        });
        console.log(dates);
        console.log(minValue);
        this.count = minValue.quantity;
      }
    },
    close() {
      if (this.isOrder || this.code === 'edit') {
        this.orderTime = [];
        this.updateForm = new SiSTKWEventsManagementUpdateHotelEntryInput();
        this.$refs['form'].resetFields();
      }
      this.dialogVisible = false;
    },
    submit() {
      var that = this;
      that.loading = true;
      const _valid = that.updateForm.extraBedNumber > that.updateForm.reserveNumber;
      if (_valid && that.updateForm.hasExtraBed) {
        that.loading = false;
        that.$message({ type: 'error', message: '加床数量超额，每个房间只能添加一张床！' });
        return;
      }
      if (!that.updateForm.hasExtraBed) {
        that.updateForm.extraBedNumber = 0;
      }
      that.$refs['form'].validate(valid => {
        if (valid) {
          if (that.code === 'order') {
            CopyData(that.updateForm, that.createForm);
            that.createForm.logisticEntryId = that.entryId;
            that.createForm.competitionId = this.$route.query.id;
            that.createForm.launchedRoomId = that.room.id;
            that.createForm.extraBedNumber = that.createForm.extraBedNumber || 0;
            api_POST_EventsManagementHotelEntryHotelEntry(that.createForm).then(res => {
              that.loading = false;
              if (res) {
                that.$message({ type: 'success', message: '预定成功！' });
                that.$parent.getOrderData();
              }
              that.orderTime = [];
              that.updateForm = new SiSTKWEventsManagementUpdateHotelEntryInput();
              that.$refs['form'].resetFields();
              that.dialogVisible = false;
            }, (error) => {
              that.loading = false;
              that.$message({ type: 'error', message: error.error.message || '预定房间失败！' });
            });
          } else {
            api_PUT_EventsManagementHotelEntryHotelEntryHotelEntryId(that.entryId, that.updateForm).then(res => {
              that.loading = false;
              if (res) {
                that.$message({ type: 'success', message: '修改成功！' });
                that.$parent.getOrderData();
              }
              that.orderTime = [];
              that.updateForm = new SiSTKWEventsManagementUpdateHotelEntryInput();
              that.$refs['form'].resetFields();
              that.dialogVisible = false;
            }, (error) => {
              that.loading = false;
              that.$message({ type: 'error', message: error.error.message || '修改失败！' });
            });
          }
        } else {
          that.loading = false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.dialog_form {
  padding: -9px 30px -20px 18px;
}
.popover {
  background: rgba(254,204,204,0.50);
  color: #8d8d8d;
  padding: 3px 5px;
  position: relative;
}
.popover:after{
  content: '';
  position:absolute;
  right: 100%;
  bottom: 5px;
  width: 0;
  height :0;
  border: 6px solid transparent;
  border-right-width: 8px;
  border-right-color: rgba(254,204,204,0.50);;
}
</style>
